<?php

namespace app\Modules\Api\controllers;

use Yii;
use app\Modules\Api\models\Saleorder;
use app\Modules\Api\models\Auction;
use app\Modules\Api\models\Product;
use app\Modules\Api\models\User;
use app\Modules\Api\models\Push;
use app\models\Banner;
use app\filters\Json;
use yii\helpers\ArrayHelper;
use yii\data\Pagination;

/**
 * Class IndexController
 * @package app\Modules\Api\controllers
 */
class IndexController extends ControllerBase
{
    public function actionIndex()
    {
        $user_id = Yii::$app->request->post('user_id',0);
        $banners = ArrayHelper::getColumn(Banner::find()->orderBy(['created_at'=>SORT_DESC])->all(),function($element){
            return Yii::$app->params['uploadUrl'].$element['img'];
        });
        //已成交
        /** @var  $done_objects  Auction[]*/
        $done_objects = Auction::find()
            ->where(['state'=>Auction::STATE_NOT_AUCTION])
            ->orderBy(['updated_at'=>SORT_DESC])
            ->limit(10)
            ->all();
        $i = 0;
        $dones = [];
        $tops = [];
        foreach($done_objects as $key=>$done_object)
        {
            if($i<3)
                $dones[] = Product::getProduct($done_object->product_id,$user_id,$done_object);

            $tops[] = $done_object->toArray(['nickname','price'],['pname','pspec']);
            $i++;
        }
        $first_auctions = Auction::getFirsts();
        //正在热拍
        $isaucs = [];
        foreach($first_auctions as $key=>$first_auction)
        {
            $isaucs[] = Product::getProduct($first_auction->product_id,$user_id);
        }
        //我在拍
        /** @var  $orders Saleorder[]*/
        $orders = Saleorder::find()->where(['user_id'=>$user_id,'state'=>Saleorder::STEAT_PATTING])->limit(20)->all();
        $myaucs = [];
        foreach($orders as $order){
            $myaucs[] = Product::getProduct($order->product_id,$user_id);
        }
        //我的收藏
        $user = User::findOne($user_id);
        $mycollects = [];
        /** @var  $collect_objects Product[]*/
        $collect_objects = $user?$user->getCollects()->all():[];
        foreach($collect_objects as $collect_object){
            $product = Product::getProduct($collect_object->pid,$user_id);
            if(is_array($product)){
                $mycollects[] = $product;
            }
        }

        $data = [
            'banners'=>$banners,
            'tops'=>$tops,
            'dones'=>$dones,
            'isaucs'=>$isaucs,
            'myaucs'=>$myaucs,
            'mycollects'=>$mycollects,
            'push_count'=>Push::getCount($user_id),
        ];

        return Json::success($data);
    }

    public function actionUpload(){
        $post = file_get_contents("php://input");
        $res = json_decode($post,true);
        $data = [];
        $path = './uploads/';
        if(!$res)
        {//iOS
            $files = Yii::$app->request->post('files');
            file_put_contents('aaa.txt',serialize($files));
            foreach ($files as $file) {
                $img = base64_decode($file['base64']);
                $ext = 'jpg';
                $savename = date('YmHis' . rand(10, 999999)) . '.' . $ext;
                file_put_contents($path . $savename, $img);
                $data[] = $savename;

            }
        }
        else
        {//android
            foreach($res as $file){
                $img = base64_decode($file);
                $ext = 'jpg';
                $savename = date('YmHis' . rand(10, 999999)) . '.' . $ext;
                file_put_contents($path . $savename, $img);
                $data[] = $savename;
            }
        }
        return Json::success($data);
    }
    //最新成交
    public function actionDone()
    {
        $query = Auction::find()->where(['state'=>Auction::STATE_NOT_AUCTION]);
        $count = $query->count();
        $pagination = new Pagination([
            'totalCount' => $count,
            'pageSize'=>Yii::$app->request->post('pageSize',15),
            'page'=>Yii::$app->request->post('page',0),
        ]);
        //已成交
        /** @var  $done_objects  Auction[]*/
        $done_objects = $query
            ->orderBy(['updated_at'=>SORT_DESC])
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        $dones = [];
        $tops = [];
        $product_fields = ['pid','name','type_id','spec'];
        $product_extraFields = ['first_pic'];
        foreach($done_objects as $key=>$done_object)
        {
            $dones[$key] = $done_object->toArray(['auctionid','nickname','market_val','price','end_at','product_id'],['cut']);
            $product_objects = Product::getProductObjects();
            $product = isset($product_objects[$done_object->product_id])
                ? $product_objects[$done_object->product_id]->toArray($product_fields,$product_extraFields):[];
            $dones[$key]['first_pic'] = $product['first_pic'];
            $dones[$key]['cut'] = $done_object->getCut();
            if($key<10)
                $tops[] = $done_object->toArray(['nickname','price'],['pname','pspec']);
        }
        $data = [
            'dones'=>$dones,
            'top'=>$tops,
            'done_count'=>strval($count),
        ];
        return Json::success($data);
    }

}